package com.zzmcc.sys.controller;

import com.jfinal.aop.Before;
import com.jfinal.plugin.activerecord.Page;
import com.zzmcc.base.BaseController;
import com.zzmcc.common.AuthorizeInterceptor;
import com.zzmcc.sys.model.Authorize;
import com.zzmcc.sys.model.Permission;
import com.zzmcc.sys.model.Role;
import com.zzmcc.sys.model.RolePermission;
import util.ChristStringUtil;
import util.ModelUtils;

import java.util.ArrayList;
import java.util.List;

@Before(AuthorizeInterceptor.class)
public class RolePermissionController extends BaseController {
    public void index(){
		StringBuffer whee = new StringBuffer();
		List<Object> param = new ArrayList<Object>();
		String tag = getPara("tag");
		if(ChristStringUtil.isNotEmpty(tag)){
			whee.append(" and actionKey like ?");
			param.add("%" + tag + "%");
		}

		Page<RolePermission> pager = RolePermission.dao.paginate(
				getParaToInt("pageNum", 1),
				getParaToInt("numPerPage", 20),
				"select a.id,b.roleid,b.name rolename,c.id pid,c.name pname,c.memo ",
				" FROM sys_role_permission a\n" +
						"LEFT JOIN sys_role b\n" +
						"on a.roleid=b.roleid\n" +
						"LEFT JOIN sys_permission c\n" +
						"on a.pid=c.id " + whee.toString(),
				param.toArray());

		setAttr("pager",pager);

		setAttr("pager",pager);
		render("../authorize_list.html");
	}
	
	public void add(){
		List<Permission> permissionList =Permission.dao.find("select * from sys_permission");
		setAttr("permissionList",permissionList);
		render("../authorize_input.html");
	}

	
	public void save(){
		RolePermission m = getModel(RolePermission.class, "rolePermission");
		m.save();
		renderDWZSuccessJson("创建成功！");
	}
	
	public void edit(){
		List<Permission> permissionList =Permission.dao.find("select * from sys_permission");
		setAttr("permissionList",permissionList);
		setAttr("rolePermission",RolePermission.dao.findById(getPara("id")));
		render("../authorize_input.html");
	}
	
	public void update(){

		RolePermission m = getModel(RolePermission.class, "rolePermission");
		m.update();
		renderDWZSuccessJson("修改成功！");
	}
	
	public void delete(){

		String[] ids = getParaValues("ids");
		StringBuffer noDeleteBuffer = new StringBuffer();
		int noDeleteCount = 0;
		int deleteCount = 0;
		for(String id:ids){
			RolePermission m = RolePermission.dao.findById(id);
			m.delete();
			deleteCount++;

		}
		renderDWZSuccessJson("操作成功，删除成功"+deleteCount+"个，失败"+noDeleteCount+"个，删除失败的用户名："+noDeleteBuffer.toString());
	}
	

	
}
